<template>
   <el-card style="height: 80px;">
      <el-form inline class="form">
         <el-form-item label="用户名：">
            <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" :disabled="keyword ? false : true" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
         </el-form-item>
      </el-form>
   </el-card>
   <el-card style="margin: 10px 0;">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button type="danger" :disabled="deleteUserArr.length ? false : true" @click="deleteUserList">批量删除用户</el-button>
      <!-- 表格展示用户信息 -->
      <el-table style="margin: 10px 0;" border :data="userArr" @selection-change="selectChange">
         <el-table-column type="selection" width="50px" align="center"></el-table-column>
         <el-table-column label="#" align="center" type="index"></el-table-column>
         <el-table-column label="ID" prop="id" width="100px"></el-table-column>
         <el-table-column label="用户名字" prop="username"></el-table-column>
         <el-table-column label="用户名称" prop="name"></el-table-column>
         <el-table-column label="用户角色" prop="roleName" show-overflow-tooltip></el-table-column>
         <el-table-column label="创建时间" prop="createTime"></el-table-column>
         <el-table-column label="更新时间" prop="updateTime"></el-table-column>
         <el-table-column label="操作" width="300px" align="center">
            <template #="{ row, $index }">
               <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
               <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
               <el-popconfirm :title="`你确定要删除${row.username}?`" width="220px" @confirm="deleteUser(row.id)">
                  <template #reference>
                     <el-button type="primary" size="small" icon="Delete">删除</el-button>
                  </template>
               </el-popconfirm>
            </template>
         </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
         layout="prev, pager, next, jumper,->,sizes,total" :total="total" @current-change="getHasUserInfo"
         @size-change="handler" />
      <!-- 抽屉组件1：完成添加账号和更新账号信息的功能 -->
      <el-drawer v-model="drawer">
         <template #header>
            <h2>{{ userParams.id ? '更新用户' : '添加用户' }}</h2>
         </template>
         <template #default>
            <div>
               <el-form :model="userParams" :rules="rules" ref="form">
                  <el-form-item label="用户姓名" prop="username">
                     <el-input placeholder="请填写用户名字" v-model="userParams.username"></el-input>
                  </el-form-item>
                  <el-form-item label="用户昵称" prop="name">
                     <el-input placeholder="请填写用户昵称" v-model="userParams.name"></el-input>
                  </el-form-item>
                  <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                     <el-input placeholder="请填写用户密码" v-model="userParams.password"></el-input>
                  </el-form-item>
               </el-form>
            </div>
         </template>
         <template #footer>
            <div style="flex: auto">
               <el-button @click="cancel">取消</el-button>
               <el-button type="primary" @click="save">确定</el-button>
            </div>
         </template>
      </el-drawer>
      <!-- 抽屉组件2：完成对已有账号的职位分配 -->
      <el-drawer v-model="drawer2">
         <template #header>
            <h4>分配角色用户(职位)</h4>
         </template>
         <template #default>
            <el-form>
               <el-form-item label="用户姓名">
                  <el-input v-model="userParams.username" disabled></el-input>
               </el-form-item>
               <el-form-item label="职位列表">
                  <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                     @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="(assignRole as any)" @change="handleAssignRoleChange">
                     <el-checkbox v-for="(item, index) in allRole" :key="item.id" :label="item">{{
                        item.roleName }}</el-checkbox>
                  </el-checkbox-group>
               </el-form-item>
            </el-form>
         </template>
         <template #footer>
            <el-button @click="drawer2 = false">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
         </template>
      </el-drawer>
   </el-card>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { reqUserInfo, reqAddOrUpdateUserInfo, reqGetRoleInfo, reqSetRole, reqRemoveUser, reqRemoveUserList } from '@/api/acl/user'
import type { Records, User, Role, SetRoleData } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'
// 分页器当前页码
let pageNo = ref<number>(1)
// 每页显示数据条数
let pageSize = ref<number>(5)
// 数据总条数
let total = ref<number>(0)
// 存储全部用户的数组
let userArr = ref<Records>([])
// 控制抽屉1的显示和隐藏
let drawer = ref<boolean>(false)
// 控制抽屉2的显示和隐藏
let drawer2 = ref<boolean>(false)
// 收集用户信息的响应式数据
let userParams = reactive<User>({
   username: '',
   name: '',
   password: ''
})
// 存储全部职位的数据
let allRole = ref<Role[]>([])
// 当前用户已有职位数据
let assignRole = ref<Role[]>([])
// 获取表单组件实例
let form = ref<any>()
// 准备一个数组存储批量删除的用户
let deleteUserArr = ref<Records>([])
// 控制全选
let checkAll = ref(false)
// 设置不确定状态的样式
let isIndeterminate = ref(true)
// 定义响应式数据：收集用户输入进来的关键字
let keyword = ref<string>('')
// 获取模板setting仓库
let settingStore = useLayOutSettingStore()
// 获取全部已有的用户信息的方法
const getHasUserInfo = async (pager = 1) => {
   pageNo.value = pager
   let result = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
   if (result.code == 200) {
      total.value = result.data.total
      userArr.value = result.data.records
   }
}
onMounted(() => {
   getHasUserInfo()
})
// 分页器下拉菜单自定义事件的回调
const handler = () => {
   getHasUserInfo()
}
// 添加用户按钮的回调
const addUser = () => {
   drawer.value = true
   // 清空数据
   Object.assign(userParams, {
      id: 0,
      username: '',
      name: '',
      password: ''
   })
   // 清除上一次的错误提示信息
   nextTick(() => {
      form.value.clearValidate('username')
      form.value.clearValidate('name')
      form.value.clearValidate('password')
   })
}
// 编辑按钮的回调
// row:用户的账号信息
const updateUser = (row: User) => {
   drawer.value = true
   // 存储当前用户的账号信息
   Object.assign(userParams, row)
   // 清除上一次的错误提示信息
   nextTick(() => {
      form.value.clearValidate('username')
      form.value.clearValidate('name')
   })
}
// 保存按钮的回调
const save = async () => {
   // 保证表单规则符合才发起请求
   await form.value.validate()
   // 添加新用户|更新已有用户信息
   let result = await reqAddOrUpdateUserInfo(userParams)
   if (result.code == 200) {
      drawer.value = false
      ElMessage.success(userParams.id ? '修改成功！' : '添加成功！')
      // 获取最新账号信息
      // getHasUserInfo(userParams.id ? pageNo.value : 1)
      // 浏览器自动刷新一次
      window.location.reload()
   } else {
      drawer.value = false
      ElMessage.error(userParams.id ? '修改失败！' : '添加失败！')
   }
}
// 取消按钮的回调
const cancel = () => {
   drawer.value = false
}
// 校验用户名字的回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
   if (value.trim().length >= 5) {
      callBack()
   } else {
      callBack(new Error('用户名字至少五位！'))
   }
}
// 校验用户昵称的回调函数
const validatorName = (rule: any, value: any, callBack: any) => {
   if (value.trim().length >= 5) {
      callBack()
   } else {
      callBack(new Error('用户昵称至少五位！'))
   }
}
// 校验用户密码的回调函数
const validatorPassword = (rule: any, value: any, callBack: any) => {
   if (value.trim().length >= 6) {
      callBack()
   } else {
      callBack(new Error('用户密码至少六位！'))
   }
}
// 表单校验的规则对象
const rules = {
   // 用户名字
   username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
   // 用户昵称
   name: [{ required: true, trigger: 'blur', validator: validatorName }],
   // 用户密码
   password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
// 分配角色按钮的回调
const setRole = async (row: User) => {
   Object.assign(userParams, row)
   let result = await reqGetRoleInfo((userParams.id as number))
   if (result.code == 200) {
      // 存储数据
      allRole.value = result.data.allRolesList
      assignRole.value = result.data.assignRoles
      drawer2.value = true
   }
}
// 全选复选框的change事件
const handleCheckAllChange = (value: any) => {
   assignRole.value = value ? allRole.value : []
   isIndeterminate.value = false
}
// 角色复选框的change事件
const handleAssignRoleChange = (value: any[]) => {
   const checkedCount = value.length
   checkAll.value = checkedCount === allRole.value.length
   isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
// 分配职位确定按钮的回调
const confirm = async () => {
   // 收集参数
   let data: SetRoleData = {
      userId: (userParams.id) as number,
      roleIdList: assignRole.value.map(item => (item.id as number))
   }
   // 发起请求
   let result = await reqSetRole(data)
   if (result.code == 200) {
      ElMessage.success('分配职位成功！')
      drawer2.value = false
      // 获取最新数据
      getHasUserInfo(pageNo.value)
   } else {
      ElMessage.error('分配职位失败！')
      drawer2.value = false
   }
}
// 删除用户按钮的回调
const deleteUser = async (userId: number) => {
   let result = await reqRemoveUser(userId)
   if (result.code == 200) {
      ElMessage.success('删除成功！')
      // 重新获取用户信息
      getHasUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
   } else {
      ElMessage.error('删除失败！')
   }
}
// table复选框勾选时会触发的事件回调
const selectChange = (value: any) => {
   deleteUserArr.value = value
}
// 批量删除按钮的回调
const deleteUserList = async () => {
   // 整理批量删除的参数
   let idList: any = deleteUserArr.value.map(item => item.id)
   let result = await reqRemoveUserList(idList)
   if (result.code == 200) {
      ElMessage.success('批量删除成功！')
      // 重新获取用户信息
      getHasUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
   } else {
      ElMessage.error('批量删除失败！')
   }
}
// 搜索按钮的回调
const search = () => {
   // 根据关键字获取用户数据
   getHasUserInfo()
   keyword.value = ''
}
// 重置按钮的回调
const reset = () => {
   settingStore.refresh = !settingStore.refresh
}
</script>

<style lang="scss" scoped>
.form {
   display: flex;
   justify-content: space-between;
   align-items: center;
}
</style>